import { defineStore } from 'pinia'
import request from '@/utils/request'

// 定义消息接口
interface Message {
  id: number
  from_uid: number
  to_uids: string
  title: string
  content: string
  file_ids: string
  is_draft: number
  send_time: number
  create_time: number
  update_time: number
  delete_time: number
  clear_time: number
  // 扩展字段
  from_name?: string
  read_user_names?: string
}

// 定义收件接口
interface Msg {
  id: number
  message_id: number
  from_uid: number
  to_uid: number
  title: string
  content: string
  file_ids: string
  is_star: number
  read_time: number
  send_time: number
  create_time: number
  delete_time: number
  clear_time: number
  // 扩展字段
  from_name?: string
  sourse?: string
  types?: number
}

// 定义统计数据接口
interface Statistics {
  msg_num: number
}

// 定义首页统计数据接口
interface HomeStatistics {
  total: Array<{ name: string; num: number }>
  handle: Array<{ name: string; num: number; id: number; url: string }>
  todue: Array<{ name: string; num: number; id: number; url: string }>
  schedule: Array<{
    id: number
    admin_id: number
    content: string
    start_time: number
    end_time: number
    start_time_format: string
    end_time_format: string
  }>

  // 最新动态数据
  dynamics: Array<{
    id: number
    time: string
    content: string
  }>
}

// 最新动态接口
interface ActivityData {
  id: number
  user_name: string
  action: string
  target_name: string
  create_time: string
  target_type: string
}

// 快捷入口接口
interface QuickAccessItem {
  id: number
  name: string
  icon: string
  url: string
}

// 定义API响应类型
interface ApiResponse<T> {
  code: number
  msg: string
  data: T
  count: number
}

interface HomeState {
  statistics: Statistics | null
  homeStatistics: HomeStatistics | null
  messages: Message[]
  messageTotal: number
  msgs: Msg[]
  msgTotal: number
}

// 首页相关API
const homeApi = {
  // 获取首页统计数据
  getHomeStatistics: (): Promise<ApiResponse<HomeStatistics>> => {
    return request({
      url: '/api/home/index/main',
      method: 'get',
    })
  },

  // 获取未读消息统计
  getUnreadStatistics: (): Promise<ApiResponse<Statistics>> => {
    return request({
      url: '/api/home/index/index',
      method: 'get',
    })
  },

  // 获取收件箱列表
  getInboxList: (params: any): Promise<ApiResponse<Msg[]>> => {
    return request({
      url: '/api/home/message/inbox',
      method: 'get',
      params,
    })
  },

  // 获取发件箱列表
  getSendboxList: (params: any): Promise<ApiResponse<Message[]>> => {
    return request({
      url: '/api/home/message/sendbox',
      method: 'get',
      params,
    })
  },

  // 获取草稿箱列表
  getDraftList: (params: any): Promise<ApiResponse<Message[]>> => {
    return request({
      url: '/api/home/message/draft',
      method: 'get',
      params,
    })
  },

  // 获取星标信息列表
  getStarList: (params: any): Promise<ApiResponse<Msg[]>> => {
    return request({
      url: '/api/home/message/star',
      method: 'get',
      params,
    })
  },

  // 获取垃圾箱列表
  getRubbishList: (params: any): Promise<ApiResponse<any[]>> => {
    return request({
      url: '/api/home/message/rubbish',
      method: 'get',
      params,
    })
  },

  // 查看收件
  readMsg: (id: number): Promise<ApiResponse<Msg>> => {
    return request({
      url: `/api/home/message/read/${id}`,
      method: 'get',
    })
  },

  // 查看发件
  viewMessage: (id: number): Promise<ApiResponse<Message>> => {
    return request({
      url: `/api/home/message/view/${id}`,
      method: 'get',
    })
  },

  // 新增/编辑信息
  saveMessage: (data: any) => {
    return request({
      url: '/api/home/message/save',
      method: 'post',
      data,
    })
  },

  // 发送消息
  sendMessage: (id: number) => {
    return request({
      url: `/api/home/message/send_message/${id}`,
      method: 'post',
    })
  },

  // 删除发件、草稿
  deleteMessage: (data: any) => {
    return request({
      url: '/api/home/message/del',
      method: 'post',
      data,
    })
  },

  // 状态修改
  updateMsgStatus: (data: any) => {
    return request({
      url: '/api/home/message/check',
      method: 'post',
      data,
    })
  },

  // 还原消息
  recoveryMessage: (data: any) => {
    return request({
      url: '/api/home/message/recovery',
      method: 'post',
      data,
    })
  },

  // 清除消息
  clearMessage: (data: any) => {
    return request({
      url: '/api/home/message/clear',
      method: 'post',
      data,
    })
  },

  // 修改个人信息
  editPersonal: (data: any) => {
    return request({
      url: '/api/home/index/edit_personal',
      method: 'post',
      data,
    })
  },

  // 获取最新动态数据 - 临时返回mock数据，因为后端API不存在
  getLatestActivities: (): Promise<ApiResponse<ActivityData[]>> => {
    return new Promise(resolve => {
      resolve({
        code: 0,
        msg: 'success',
        data: [],
        count: 0,
      })
    })
  },

  // 获取审批数据
  getApprovalList: (): Promise<ApiResponse<any[]>> => {
    return request({
      url: '/api/approval/list',
      method: 'get',
    })
  },

  // 修改密码
  editPassword: (data: any) => {
    return request({
      url: '/api/home/index/edit_password',
      method: 'post',
      data,
    })
  },
}

export const useHomeStore = defineStore('home', {
  state: (): HomeState => ({
    statistics: null,
    homeStatistics: null,
    messages: [],
    messageTotal: 0,
    msgs: [],
    msgTotal: 0,
  }),

  actions: {
    // 获取首页统计数据
    async getHomeStatisticsAction() {
      try {
        const res = await homeApi.getHomeStatistics()
        if (res.code === 0) {
          this.homeStatistics = res.data
        } else {
          // 处理非成功响应
        }
        return res
      } catch (error) {
        throw error
      }
    },

    // 获取未读消息统计
    async getUnreadStatisticsAction() {
      try {
        const res = await homeApi.getUnreadStatistics()
        if (res.code === 0) {
          this.statistics = res.data
        }
        return res
      } catch (error) {
        throw error
      }
    },

    // 获取收件箱列表
    async getInboxListAction(params: any) {
      try {
        const res = await homeApi.getInboxList(params)
        if (res.code === 0) {
          this.msgs = res.data
          this.msgTotal = res.count
        }
        return res
      } catch (error) {
        throw error
      }
    },

    // 获取发件箱列表
    async getSendboxListAction(params: any) {
      try {
        const res = await homeApi.getSendboxList(params)
        if (res.code === 0) {
          this.messages = res.data
          this.messageTotal = res.count
        }
        return res
      } catch (error) {
        throw error
      }
    },

    // 获取草稿箱列表
    async getDraftListAction(params: any) {
      try {
        const res = await homeApi.getDraftList(params)
        if (res.code === 0) {
          this.messages = res.data
          this.messageTotal = res.count
        }
        return res
      } catch (error) {
        throw error
      }
    },

    // 获取星标信息列表
    async getStarListAction(params: any) {
      try {
        const res = await homeApi.getStarList(params)
        if (res.code === 0) {
          this.msgs = res.data
          this.msgTotal = res.count
        }
        return res
      } catch (error) {
        throw error
      }
    },

    // 获取垃圾箱列表
    async getRubbishListAction(params: any) {
      try {
        const res = await homeApi.getRubbishList(params)
        if (res.code === 0) {
          // 垃圾箱数据混合了message和msg表的数据
          this.messages = res.data as any
          this.messageTotal = res.count
        }
        return res
      } catch (error) {
        throw error
      }
    },

    // 查看收件
    async readMsgAction(id: number) {
      try {
        const res = await homeApi.readMsg(id)
        return res
      } catch (error) {
        throw error
      }
    },

    // 查看发件
    async viewMessageAction(id: number) {
      try {
        const res = await homeApi.viewMessage(id)
        return res
      } catch (error) {
        throw error
      }
    },

    // 新增/编辑信息
    async saveMessageAction(data: any) {
      try {
        const res = await homeApi.saveMessage(data)
        return res
      } catch (error) {
        throw error
      }
    },

    // 发送消息
    async sendMessageAction(id: number) {
      try {
        const res = await homeApi.sendMessage(id)
        return res
      } catch (error) {
        throw error
      }
    },

    // 删除发件、草稿
    async deleteMessageAction(data: any) {
      try {
        const res = await homeApi.deleteMessage(data)
        return res
      } catch (error) {
        throw error
      }
    },

    // 状态修改
    async updateMsgStatusAction(data: any) {
      try {
        const res = await homeApi.updateMsgStatus(data)
        return res
      } catch (error) {
        throw error
      }
    },

    // 还原消息
    async recoveryMessageAction(data: any) {
      try {
        const res = await homeApi.recoveryMessage(data)
        return res
      } catch (error) {
        throw error
      }
    },

    // 清除消息
    async clearMessageAction(data: any) {
      try {
        const res = await homeApi.clearMessage(data)
        return res
      } catch (error) {
        throw error
      }
    },

    // 修改个人信息
    async editPersonalAction(data: any) {
      try {
        const res = await homeApi.editPersonal(data)
        return res
      } catch (error) {
        throw error
      }
    },

    // 修改密码
    async editPasswordAction(data: any) {
      try {
        const res = await homeApi.editPassword(data)
        return res
      } catch (error) {
        throw error
      }
    },

    /**
     * 获取最新动态数据
     */
    async getLatestActivitiesAction() {
      try {
        const res = await homeApi.getLatestActivities()
        return res
      } catch (error) {
        throw error
      }
    },

    /**
     * 获取审批数据
     */
    async getApprovalListAction() {
      try {
        const res = await homeApi.getApprovalList()
        return res
      } catch (error) {
        throw error
      }
    },
  },
})
